<script lang="ts" setup>
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { listConfig, configExport, delConfig, refreshCache } from '@/api/system/config/index'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { downloadBlobFile } from '@/utils'
import { checkPermission } from '@/utils/permission'
import EditDialog from './components/EditDialog.vue'
import type { ConfigList, QueryParams } from '@/api/system/config/type'
import { debounce } from 'es-toolkit'
import { formatDate } from '@/utils/day'

// 处理日期范围参数的工具方法
const processDateRangeParams = (params: any) => {
	const processedParams = { ...params }
	if (processedParams.daterange) {
		processedParams['params[beginTime]'] = processedParams.daterange[0]
		processedParams['params[endTime]'] = processedParams.daterange[1]
		delete processedParams.daterange
	}
	return processedParams
}

// form
const formValue = ref<QueryParams>({
	configName: '',
	configKey: '',
	configType: '',
	daterange: undefined
})

const sysYesNo = ref<IGetDictsRes>([])

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '参数名称',
		prop: 'configName'
	},
	{
		type: 'input',
		label: '参数键名',
		prop: 'configKey'
	},
	{
		type: 'select',
		label: '系统内置',
		prop: 'configType',
		options: sysYesNo as unknown as any,
		attrs: {
			style: {
				width: '200px'
			}
		}
	},
	{
		type: 'date-picker',
		label: '创建时间',
		prop: 'daterange',
		attrs: {
			type: 'datetimerange',
			'range-separator': '至',
			'start-placeholder': '开始日期',
			'end-placeholder': '结束日期',
			'value-format': 'YYYY-MM-DD HH:mm:ss'
		}
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<ConfigList[]>([])
const selectedRows = ref<ConfigList[]>([])

const columns = ref<TableColums[]>([
	{
		type: 'selection',
		width: 50,
		align: 'center'
	},
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '参数主键',
		prop: 'id'
	},
	{
		label: '参数名称',
		prop: 'configName'
	},
	{
		label: '参数键名',
		prop: 'configKey'
	},
	{
		label: '参数键值',
		prop: 'configValue'
	},
	{
		label: '系统内置',
		prop: 'configType',
		align: 'center'
	},
	{
		label: '备注',
		prop: 'remark'
	},
	{
		label: '创建时间',
		prop: 'createTime',
		formatter: row => formatDate(row.createTime)
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 160,
		align: 'center'
	}
])

// 多选
const multiple = computed(() => selectedRows.value.length < 1)
const single = computed(() => selectedRows.value.length !== 1)

const handleSelectionChange = (selection: ConfigList[]) => {
	selectedRows.value = selection
}

// dialog
const editDialogRef = useTemplateRef('editDialogRef')

const getTableData = async () => {
	loading.value = true
	try {
		const params = processDateRangeParams({
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value
		})

		const res = await listConfig(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}

const handleAdd = () => {
	editDialogRef.value?.init('add')
}

const handleEdit = (row: ConfigList) => {
	// 确保 configId 为字符串类型
	const editForm = {
		...row
	}
	editDialogRef.value?.init('edit', editForm)
}

const handleEditSelected = () => {
	if (selectedRows.value.length === 1) {
		handleEdit(selectedRows.value[0])
	}
}

const handleDelete = async (row?: ConfigList) => {
	let ids: string
	let message: string

	if (row) {
		ids = String(row.id)
		message = `是否确认删除参数编号为"${ids}"的数据项？`
	} else {
		ids = selectedRows.value.map(item => String(item.id)).join(',')
		message = `是否确认删除选中的${selectedRows.value.length}条数据？`
	}

	await ElMessageBox({
		title: '提示',
		type: 'warning',
		message,
		showCancelButton: true,
		cancelButtonText: '取消',
		confirmButtonText: '确定'
	})

	await delConfig(ids)
	ElMessage.success('删除成功')
	getTableData()
}

const handleDeleteSelected = async () => {
	if (selectedRows.value.length > 0) {
		await handleDelete()
	}
}

const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

const exportFn = async () => {
	const params = processDateRangeParams({ ...formValue.value })
	const data = await configExport(params)

	downloadBlobFile(data.data, data.filename ? data.filename : `config_${new Date().getTime()}.xlsx`)
}

const handleRefreshCache = async () => {
	await refreshCache()
	ElMessage.success('刷新缓存成功')
}

const init = async () => {
	// 获取字典数据
	const dictData = await getDicts('sys_sys_yes_no')
	sysYesNo.value = dictData
	// 获取表格数据
	await getTableData()
}

onMounted(() => {
	init()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
				@selectionChange="handleSelectionChange"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['system:config:add'])"
						type="primary"
						@click="handleAdd"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['system:config:edit'])"
						:disabled="single"
						@click="handleEditSelected"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['system:config:remove'])"
						:disabled="multiple"
						@click="handleDeleteSelected"
					>
						删除
					</el-button>
					<el-button
						v-if="checkPermission(['system:config:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
					<el-button
						v-if="checkPermission(['system:config:remove'])"
						@click="handleRefreshCache"
					>
						刷新缓存
					</el-button>
				</template>
				<template #configType="{ row }">
					<DictTag
						:options="sysYesNo"
						:value="row.configType"
					/>
				</template>

				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:config:edit'])"
						type="primary"
						link
						@click="handleEdit(row)"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['system:config:remove'])"
						type="danger"
						link
						@click="handleDelete(row)"
					>
						删除
					</el-button>
				</template>
			</QTable>
		</div>
		<EditDialog
			ref="editDialogRef"
			:sys-yes-no="sysYesNo"
			@refresh="getTableData"
		/>
	</div>
</template>
